package com.spzx.common.core.utils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolUtil {
    private static ThreadPoolExecutor threadPoolExecutor;
    private ThreadPoolUtil(){

    }

    public static ThreadPoolExecutor getExecutor(){
        if(threadPoolExecutor!=null){
            return threadPoolExecutor;
        }
        synchronized (ThreadPoolUtil.class){
            if(threadPoolExecutor!=null){
                return threadPoolExecutor;
            }
            //cpu的核心数
            int processors = Runtime.getRuntime().availableProcessors();
            threadPoolExecutor = new ThreadPoolExecutor(
                    processors*2, //核心线程
                    processors*2, //最大线程数
                    60,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(300),
                    new ThreadPoolExecutor.CallerRunsPolicy(){ //拒绝处理器
                        @Override
                        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                            try {
                                Thread.sleep(300);
                                e.execute(r); //让线程池再次尝试执行 被拒绝的任务
                            } catch (InterruptedException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    }

            );
            return threadPoolExecutor;
        }
    }
}
